<template>
  <div class="admin-notification-center">
    <h1>管理员通知中心</h1>

    <!-- 功能标签页 -->
    <div class="tabs">
      <button
        class="tab-btn"
        :class="{ active: activeTab === 'permission' }"
        @click="activeTab = 'permission'"
      >
        权限申请管理
      </button>
      <button
        class="tab-btn"
        :class="{ active: activeTab === 'publish' }"
        @click="activeTab = 'publish'"
      >
        发布通知
      </button>
    </div>

    <!-- 权限申请管理模块 -->
    <div v-if="activeTab === 'permission'" class="permission-module">
      <div class="filter-controls">
        <select v-model="filterStatus" @change="fetchPermissionApplications">
          <option value="all">全部申请</option>
          <option value="pending">待审批</option>
          <option value="approved">已通过</option>
          <option value="rejected">已拒绝</option>
        </select>
        <button @click="fetchPermissionApplications">刷新列表</button>
      </div>

      <div class="application-list">
        <div class="application-header">
          <div class="col-applicant">申请人</div>
          <div class="col-applied-user">申请新增用户</div>
          <div class="col-time">申请时间</div>
          <div class="col-status">状态</div>
          <div class="col-action">操作</div>
        </div>

        <div v-for="app in permissionApplications" :key="app.id" class="application-item">
          <div class="col-applicant">
            <div class="name">{{ app.applicantName }}</div>
            <div class="contact">{{ app.applicantPhone }}</div>
          </div>
          <div class="col-applied-user">
            <div class="name">{{ app.newUserName }}</div>
            <div class="relation">{{ app.relationship }} | {{ app.newUserPhone }}</div>
          </div>
          <div class="col-time">{{ formatDate(app.applyTime) }}</div>
          <div class="col-status">
            <span :class="statusClass(app.status)">{{ statusText(app.status) }}</span>
          </div>
          <div class="col-action">
            <template v-if="app.status === 'pending'">
              <button class="approve-btn" @click="handleApprove(app.id)">通过</button>
              <button class="reject-btn" @click="showRejectReason(app.id)">拒绝</button>
            </template>
            <template v-else>
              <button class="view-btn" @click="viewApplicationDetail(app)">查看</button>
            </template>
          </div>
        </div>

        <div v-if="permissionApplications.length === 0" class="empty-state">暂无权限申请记录</div>
      </div>
    </div>

    <!-- 发布通知模块 -->
    <div v-if="activeTab === 'publish'" class="publish-module">
      <div class="notification-form">
        <div class="form-group">
          <label>通知标题 <span class="required">*</span></label>
          <input type="text" v-model="notificationForm.title" placeholder="请输入通知标题" />
        </div>

        <div class="form-group">
          <label>通知内容 <span class="required">*</span></label>
          <textarea
            v-model="notificationForm.content"
            placeholder="请输入通知内容"
            rows="8"
          ></textarea>
        </div>

        <div class="form-actions">
          <button @click="resetNotificationForm">重置</button>
          <button @click="submitNotification" class="submit-btn">发布通知</button>
        </div>
      </div>

      <div class="history-notifications">
        <h3>历史发布记录</h3>
        <div class="notification-list">
          <div v-for="noti in historyNotifications" :key="noti.id" class="notification-item">
            <div class="noti-header">
              <div class="noti-title">{{ noti.title }}</div>
              <div class="noti-time">{{ formatDate(noti.publishTime) }}</div>
            </div>
            <div class="noti-content">{{ noti.content }}</div>
            <div class="noti-meta">
              <span>发布范围: 所有用户</span>
            </div>
          </div>

          <div v-if="historyNotifications.length === 0" class="empty-state">暂无发布记录</div>
        </div>
      </div>
    </div>

    <!-- 拒绝原因弹窗 -->
    <div v-if="showRejectDialog" class="dialog-overlay">
      <div class="dialog-content">
        <h3>拒绝原因</h3>
        <textarea v-model="rejectReason" placeholder="请输入拒绝原因" rows="4"></textarea>
        <div class="dialog-actions">
          <button @click="showRejectDialog = false">取消</button>
          <button @click="confirmReject">确认拒绝</button>
        </div>
      </div>
    </div>

    <!-- 申请详情弹窗 -->
    <div v-if="currentApplication" class="dialog-overlay">
      <div class="dialog-content detail-dialog">
        <h3>申请详情</h3>
        <div class="detail-item">
          <span class="detail-label">申请人:</span>
          <span class="detail-value">{{ currentApplication.applicantName }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">联系电话:</span>
          <span class="detail-value">{{ currentApplication.applicantPhone }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">住址:</span>
          <span class="detail-value">{{ currentApplication.applicantAddress }}</span>
        </div>
        <hr />
        <div class="detail-item">
          <span class="detail-label">申请新增用户:</span>
          <span class="detail-value">{{ currentApplication.newUserName }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">联系电话:</span>
          <span class="detail-value">{{ currentApplication.newUserPhone }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">与申请人关系:</span>
          <span class="detail-value">{{ currentApplication.relationship }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请时间:</span>
          <span class="detail-value">{{ formatDate(currentApplication.applyTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请状态:</span>
          <span class="detail-value" :class="statusClass(currentApplication.status)">
            {{ statusText(currentApplication.status) }}
          </span>
        </div>
        <div v-if="currentApplication.status !== 'pending'" class="detail-item">
          <span class="detail-label">处理时间:</span>
          <span class="detail-value">{{ formatDate(currentApplication.handleTime) }}</span>
        </div>
        <div v-if="currentApplication.status === 'rejected'" class="detail-item">
          <span class="detail-label">拒绝原因:</span>
          <span class="detail-value">{{ currentApplication.rejectReason }}</span>
        </div>
        <div class="dialog-actions">
          <button @click="currentApplication = null">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  apiGetPermissionApplications,
  apiApprovePermission,
  apiGetHistoryNotifications,
  apiPublishNotification,
  apiRejectPermission
} from '@/api/notification.ts'

export default {
  data() {
    return {
      // 标签页状态
      activeTab: 'permission',

      // 权限申请相关
      permissionApplications: [],
      filterStatus: 'all',
      showRejectDialog: false,
      rejectReason: '',
      currentRejectId: null,
      currentApplication: null,

      // 发布通知相关（简化，不包含发布范围）
      notificationForm: {
        title: '',
        content: '',
      },
      historyNotifications: [],
    }
  },
  mounted() {
    // 初始化加载数据
    this.fetchPermissionApplications()
    this.fetchHistoryNotifications()
  },
  methods: {
    /**
     * 格式化日期显示
     * @param {Number} timestamp - 时间戳
     * @returns {String} 格式化后的日期字符串
     */
    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      })
    },

    /**
     * 获取状态显示文本
     * @param {String} status - 状态值
     * @returns {String} 状态文本
     */
    statusText(status) {
      const statusMap = {
        pending: '待审批',
        approved: '已通过',
        rejected: '已拒绝',
      }
      return statusMap[status] || '未知状态'
    },

    /**
     * 获取状态样式类名
     * @param {String} status - 状态值
     * @returns {String} 样式类名
     */
    statusClass(status) {
      const classMap = {
        pending: 'status-pending',
        approved: 'status-approved',
        rejected: 'status-rejected',
      }
      return classMap[status] || ''
    },

    /**
     * 显示拒绝原因输入框
     * @param {Number} id - 申请ID
     */
    showRejectReason(id) {
      this.currentRejectId = id
      this.rejectReason = ''
      this.showRejectDialog = true
    },

    /**
     * 确认拒绝申请
     */
    confirmReject() {
      if (!this.rejectReason.trim()) {
        alert('请输入拒绝原因')
        return
      }
      this.handleReject(this.currentRejectId, this.rejectReason)
      this.showRejectDialog = false
    },

    /**
     * 查看申请详情
     * @param {Object} app - 申请对象
     */
    viewApplicationDetail(app) {
      this.currentApplication = { ...app }
    },

    /**
     * 重置通知表单
     */
    resetNotificationForm() {
      this.notificationForm = {
        title: '',
        content: '',
      }
    },

    /**
     * 提交发布通知（默认发布给所有用户）
     */
    submitNotification() {
      if (!this.notificationForm.title.trim()) {
        alert('请输入通知标题')
        return
      }
      if (!this.notificationForm.content.trim()) {
        alert('请输入通知内容')
        return
      }

      // 补充默认发布范围为“所有用户”
      const notificationData = {
        ...this.notificationForm,
        scope: 'all',
      }

      apiPublishNotification(notificationData)
        .then(() => {
          alert('通知发布成功（已发送给所有用户）')
          this.resetNotificationForm()
          this.fetchHistoryNotifications()
        })
        .catch(() => {
          alert('通知发布失败，请重试')
        })
    },

    /**
     * 后端接口：获取权限申请列表
     * 作用：从服务器获取权限申请列表，支持按状态筛选
     * 参数：
     *   status - 筛选状态（all/pending/approved/rejected）
     * 返回：权限申请数组
     */
    async fetchPermissionApplications() {
      try {
        const result = await apiGetPermissionApplications(this.filterStatus)
        this.permissionApplications = result
      } catch (error) {
        console.error('获取权限申请列表失败', error)
        alert('获取权限申请列表失败，请重试')
      }
    },

    /**
     * 后端接口：审批通过权限申请
     * 作用：通知服务器审批通过指定ID的权限申请，系统将创建新用户
     * 参数：
     *   id - 权限申请ID
     * 返回：操作结果
     */
    async handleApprove(id) {
      if (confirm('确定要通过此权限申请吗？通过后将创建新用户')) {
        try {
          await apiApprovePermission(id)
          alert('审批已通过')
          this.fetchPermissionApplications()
        } catch (error) {
          console.error('审批通过失败', error)
          alert('操作失败，请重试')
        }
      }
    },

    /**
     * 后端接口：拒绝权限申请
     * 作用：通知服务器拒绝指定ID的权限申请，并记录拒绝原因
     * 参数：
     *   id - 权限申请ID
     *   reason - 拒绝原因
     * 返回：操作结果
     */
    async handleReject(id, reason) {
      try {
        await apiRejectPermission(id, reason)
        alert('已拒绝申请并通知用户')
        await this.fetchPermissionApplications()
      } catch (error) {
        console.error('拒绝申请失败', error)
        alert('操作失败，请重试')
      }
    },

    /**
     * 后端接口：获取历史通知列表
     * 作用：从服务器获取管理员已发布的通知历史记录
     * 参数：无
     * 返回：通知数组
     */
    async fetchHistoryNotifications() {
      try {
        const result = await apiGetHistoryNotifications()
        this.historyNotifications = result
      } catch (error) {
        console.error('获取历史通知失败', error)
        alert('获取历史通知失败，请重试')
      }
    },

  },
}
</script>

<style scoped>
.admin-notification-center {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px 30px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

h1 {
  color: #2c3e50;
  margin-bottom: 25px;
  font-weight: 600;
}

/* 标签页样式 */
.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e1e4e8;
}

.tab-btn {
  padding: 10px 20px;
  background: none;
  border: none;
  font-size: 16px;
  font-weight: 500;
  color: #6c757d;
  cursor: pointer;
  margin-bottom: -1px;
  transition: all 0.2s;
}

.tab-btn.active {
  color: #1890ff;
  border-bottom: 2px solid #1890ff;
}

.tab-btn:hover:not(.active) {
  color: #343a40;
  background-color: #f8f9fa;
}

/* 通用样式 */
button {
  padding: 6px 12px;
  border-radius: 4px;
  border: 1px solid transparent;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

button:hover {
  opacity: 0.9;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #6c757d;
  border: 1px dashed #e1e4e8;
  margin-top: 10px;
}

/* 权限申请模块 */
.permission-module {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.filter-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.filter-controls select {
  padding: 6px 10px;
  border-radius: 4px;
  border: 1px solid #ced4da;
}

.application-header,
.application-item {
  display: flex;
  padding: 12px 15px;
  border-bottom: 1px solid #e1e4e8;
}

.application-header {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.application-item:last-child {
  border-bottom: none;
}

.application-item:hover {
  background-color: #f8f9fa;
}

.col-applicant {
  width: 200px;
  flex-shrink: 0;
}

.col-applied-user {
  flex-grow: 1;
  min-width: 250px;
}

.col-time {
  width: 180px;
  flex-shrink: 0;
}

.col-status {
  width: 120px;
  flex-shrink: 0;
}

.col-action {
  width: 180px;
  flex-shrink: 0;
  display: flex;
  gap: 8px;
  justify-content: center;
}

.name {
  font-weight: 500;
  margin-bottom: 4px;
}

.contact,
.relation {
  font-size: 13px;
  color: #6c757d;
}

.status-pending {
  color: #ffc107;
  background-color: rgba(255, 193, 7, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 13px;
}

.status-approved {
  color: #28a745;
  background-color: rgba(40, 167, 69, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 13px;
}

.status-rejected {
  color: #f56c6c;
  background-color: rgba(220, 53, 69, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 13px;
}

.approve-btn {
  background-color: #28a745;
  color: white;
  border: none;
}

.reject-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
}

.view-btn {
  background-color: #1890ff;
  color: white;
  border: none;
}

.approve-btn,
.reject-btn,
.view-btn {
  height: 35px; /* 数值越小，按钮越矮（建议20-24px） */
  min-height: 24px; /* 防止被内容撑开 */
  padding: 0 10px; /* 取消上下内边距，只保留左右 */
  font-size: 14px; /* 文字适配小按钮 */
  line-height: 24px; /* 文字垂直居中（与height一致） */
  display: inline-block; /* 确保高度生效 */
}

/* 发布通知模块 */
.publish-module {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.notification-form {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e1e4e8;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #495057;
}

.required {
  color: #f56c6c;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.form-actions button {
  background-color: #6c757d;
  color: white;
  border: none;
}

.submit-btn {
  background-color: #1890ff !important;
}

.history-notifications h3 {
  margin-top: 0;
  color: #2c3e50;
  margin-bottom: 15px;
}

.notification-item {
  padding: 15px;
  border: 1px solid #e1e4e8;
  border-radius: 4px;
  margin-bottom: 10px;
}

.notification-item:hover {
  border-color: #1890ff;
}

.noti-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.noti-title {
  font-weight: 600;
  color: #2c3e50;
}

.noti-time {
  font-size: 13px;
  color: #6c757d;
}

.noti-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.noti-meta {
  font-size: 13px;
  color: #6c757d;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 6px;
  width: 90%;
  max-width: 500px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.detail-dialog {
  max-width: 600px;
}

.dialog-content h3 {
  margin-top: 0;
  color: #2c3e50;
  margin-bottom: 15px;
}

.dialog-content textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.dialog-actions button {
  background-color: #6c757d;
  color: white;
  border: none;
}

.dialog-actions button:last-child {
  background-color: #1890ff;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
}

.detail-label {
  width: 100px;
  flex-shrink: 0;
  font-weight: 500;
  color: #495057;
}

.detail-value {
  flex-grow: 1;
}
</style>
